package edu.rit.teamrocket.model;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FoodCollection implements FoodDAO
{
	final String FILE_NAME = "foodCollection.log";
	private List<Entry> foods;
	
	public FoodCollection() {
		
		foods = new ArrayList<Entry>();
		
	}

	@Override
	public List<Entry> getFoods()
	{
		return this.foods;
	}

	@Override
	public void addFood(Entry newEntry)
	{
		foods.add(newEntry);
	}

	@Override
	public boolean removeFood(Entry entryToRemove)
	{
		foods.remove(entryToRemove);
		return true;
	}

	public void writeToFile()
	{
		File file = new File(FILE_NAME);

		if(file != null)
		{
			try
			{
				FileOutputStream out = new FileOutputStream(file); 
				ObjectOutputStream objectsOut = new ObjectOutputStream(out);
				for(int i = 0; i < foods.size(); i++) 
				{
					objectsOut.writeObject(foods.get(i));
				}
				objectsOut.flush(); 
				objectsOut.close();
			} 

			catch (Exception exception)
			{
				System.err.println("Something went wrong: " + exception.getMessage());
			} 
		} 
	}

	public List<Entry> readFromFile()
	{
		try
		{
			FileInputStream in = new FileInputStream(FILE_NAME);
			ObjectInputStream objectsIn = new ObjectInputStream(in);
			Entry object = null;
			while((object  = (Entry) objectsIn.readObject()) != null) {
				Entry objects = (Entry) objectsIn.readObject();
				foods.add(objects);
			}	
			
			objectsIn.close();
		}
		catch (FileNotFoundException e)
		{
			System.out.println("Something went wrong: " + e.getMessage());
		}
		catch (Exception exception)
		{
			System.out.println("Something went wrong: " + exception.getMessage());
		}

		return foods;
		
	}

}
